import blank from '@/assets/images/blank.jpg'
import store from '@/store'
import { isExternal } from '@/utils/validate'

export const exportDefault = 'export default '

export const beautifierConf = {
  html: {
    indent_size: '2',
    indent_char: ' ',
    max_preserve_newlines: '-1',
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: 'separate',
    brace_style: 'end-expand',
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: false,
    end_with_newline: true,
    wrap_line_length: '110',
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true
  },
  js: {
    indent_size: '2',
    indent_char: ' ',
    max_preserve_newlines: '-1',
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: 'normal',
    brace_style: 'end-expand',
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: true,
    end_with_newline: true,
    wrap_line_length: '110',
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true
  }
}

/**
 * 拼接图片服务器地址
 * @param src
 * @returns {string|*}
 */
export function getImageSrc(src) {
  if (!src) { return blank }
  if (isExternal(src)) {
    return src
  }
  return store.state.app.server_api + `${process.env.VUE_APP_MODULE_ADMIN_API}/public/file/preview/${src}`
}

/**
 * 拼接视频服务器地址
 * @param src
 * @returns {string|*}
 */
export function getVideoSrc(src) {
  if (!src) { return '' }
  if (isExternal(src)) {
    return src
  }
  if (src.indexOf('/') > -1) {
    return store.state.app.server_api + src
  } else {
    return store.state.app.server_api + `${process.env.VUE_APP_MODULE_ADMIN_API}/public/file/preview/${src}`
  }
}

/**
 * 转换字典文本和样式
 * @param options
 * @param value
 * @returns {(string|*)[]}
 */
export function getDictElement(options, value) {
  const index = options.findIndex(dict => {
    if (dict.dictValue + '' === value + '') {
      return true
    }
    return false
  })

  if (index !== -1) {
    const value_ = options[index].dictLabel
    const type = options[index].cssClass === 'warn' ? 'warning' : options[index].cssClass
    const color = options[index].cssClass === 'error' ? 'danger' : options[index].cssClass
    return [type, value_, color]
  } else {
    return ['', value, '']
  }
}

/**
 * 格式化时间描述
 * @param time
 * @param cFormat '{y}-{m}-{d} {h}:{i}:{s}'
 * @returns {string|null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * 格式化时间描述
 * @param time
 * @param cFormat '{y}-{m}-{d} {h}:{i}:{s}'
 * @returns {string}
 */
export function formatTime(time, cFormat) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = new Date(time.replace(/-/g, '/'))
  }

  const d = new Date(time)
  const now = Date.now()
  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (cFormat) {
    return this.parseTime(time, cFormat)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * 计算指定时间与当前的时间差
 * @param data
 * @returns {string}
 */
export function diffDateBefore(data) {
  // 获取比对时间
  const dateBegin = new Date(data.replace(/-/g, '/'))
  // 获取当前时间
  const dateEnd = new Date()
  const diffTime = dateEnd.getTime() - dateBegin.getTime()
  // 计算相差年数
  const yearDiff = Math.floor(diffTime / (365 * 24 * 3600 * 1000))
  if (yearDiff > 0) {
    return yearDiff + '年前'
  }
  // 计算剩余的毫秒数
  let mseceonds = diffTime % (365 * 24 * 3600 * 1000)
  const monthDiff = Math.floor(mseceonds / (30 * 24 * 3600 * 1000))
  if (monthDiff > 0) {
    return monthDiff + '月前'
  }
  mseceonds = mseceonds % (30 * 24 * 3600 * 1000)
  // 计算相差天数
  const dayDiff = Math.floor(mseceonds / (24 * 3600 * 1000))
  if (dayDiff > 0) {
    return dayDiff + '天前'
  }
  // 计算剩余的毫秒数
  mseceonds = mseceonds % (24 * 3600 * 1000)
  // 计算相差小时数
  const hours = Math.floor(mseceonds / (3600 * 1000))
  if (hours > 0) {
    return hours + '小时前'
  }
  // 计算小时数后剩余的毫秒数
  mseceonds = mseceonds % (3600 * 1000)
  // 计算相差分钟数
  const minutes = Math.floor(mseceonds / (60 * 1000))
  if (minutes > 0) {
    return minutes + '分钟前'
  }
  return '刚刚'
}

/**
 * 将毫秒，转换成时间字符串
 * @param ms
 * @returns {string}
 */
export function convertTimeMs(ms) {
  const day = Math.floor(ms / (24 * 60 * 60 * 1000))
  const hour =  Math.floor((ms / (60 * 60 * 1000) - day * 24))
  const minute =  Math.floor(((ms / (60 * 1000)) - day * 24 * 60 - hour * 60))
  const second =  Math.floor((ms / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60))
  if (day > 0) {
    return day + '天' + hour + '小时' + minute + '分钟'
  }
  if (hour > 0) {
    return hour + '小时' + minute + '分钟'
  }
  if (minute > 0) {
    return minute + '分钟'
  }
  if (second > 0) {
    return second + '秒'
  } else {
    return 0 + '秒'
  }
}

/**
 * 将金额分，转换成元
 * @param number
 */
export function convertPriceYuan(number) {
  const str = number / 100 + ''
  const intSum = str.substring(0, str.indexOf('.')).replace(/\B(?=(?:\d{3})+$)/g, ',')
  const dot = str.substring(str.length, str.indexOf('.'))
  return intSum + dot
}

/**
 * 计算字符串字节长度
 * @param str
 * @returns {*}
 */
export function byteLength(str) {
  let s = str.length
  for (let i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i)
    if (code > 0x7f && code <= 0x7ff) s++
    else if (code > 0x7ff && code <= 0xffff) s += 2
    if (code >= 0xDC00 && code <= 0xDFFF) i--
  }
  return s
}

/**
 * 首字母大写格式
 * @param str
 * @returns {*}
 */
export function titleCase(str) {
  return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
}

/**
 * 下划线转驼峰格式
 * @param str
 * @returns {*}
 */
export function camelCase(str) {
  return str.replace(/-[a-z]/g, str1 => str1.substr(-1).toUpperCase())
}

/**
 * 判断是否是数字
 * @param str
 * @returns {boolean}
 */
export function isNumberStr(str) {
  return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
}

export function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

/**
 * url参数转json对象
 * @param url
 * @returns {{}}
 */
export function convertObjectParam(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 * json对象转url参数
 * @param json
 * @returns {string}
 */
export function convertUrlParam(json) {
  if (!json) return ''
  return this.cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

/**
 * 获取元素内文本
 * @param val
 * @returns {string}
 */
export function getElementText(val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

export function getUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
  })
}

/**
 * 合并对象
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = this.objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

/**
 * 扩展对象属性
 * @param {Object} target
 * @param {(Object|Array)} source
 * @param {String} prefix
 * @returns {Object}
 */
export function objectExtend(target, source, prefix) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    target = source.slice()
    return target
  }
  if (prefix === undefined) {
    prefix = ''
  }
  Object.keys(source).forEach(property => {
    const targetProperty = target[prefix + property]
    if (targetProperty === null || targetProperty === undefined) {
      target[prefix + property] = {}
    }
    if (typeof property === 'object') {
      target[prefix + property] = this.objectUpdate(target[prefix + property], source[property])
    } else {
      target[prefix + property] = source[property]
    }
  })
  return target
}

/**
 * 更新对象属性
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectUpdate(target, source, updateNull = false) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(target).forEach(property => {
    const sourceProperty = source[property]
    if (sourceProperty !== null && sourceProperty !== undefined) {
      if (typeof sourceProperty === 'object') {
        target[property] = this.objectUpdate(target[property], sourceProperty)
      } else {
        target[property] = sourceProperty
      }
    } else if (updateNull) {
      target[property] = undefined
    }
  })
  return target
}

/**
 * 深拷贝对象
 * @param source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

/**
 * 延时执行方法
 * @param func
 * @param wait
 * @param immediate
 * @returns {function(...[*]=): *}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

/**
 * 添加样式
 * @param ele
 * @param cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * 移除样式
 * @param ele
 * @param cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

/**
 * 判断样式是否存在
 * @param ele
 * @param cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * 切换元素样式
 * @param element
 * @param className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

/**
 * 构造Map结构数据
 * @param str
 * @param expectsLowerCase
 * @returns {{(*): *, (*): *}}
 */
export function buildMap(str, expectsLowerCase) {
  const map = Object.create(null)
  const list = str.split(',')
  for (let i = 0; i < list.length; i++) {
    map[list[i]] = true
  }
  return expectsLowerCase
    ? val => map[val.toLowerCase()]
    : val => map[val]
}

/**
 * 构造树型结构数据
 * @param data      数据源
 * @param id        id字段
 * @param parentId  父节点字段
 * @param children  子节点字段
 * @param rootId    根Id
 */
export function buildTree(data, id, parentId, children, rootId) {
  id = id || 'id'
  parentId = parentId || 'parentId'
  children = children || 'children'
  rootId = rootId || Math.min.apply(Math, data.map(item => {
    return item[parentId]
  })) || 0
  //对源数据深度克隆
  const cloneData = JSON.parse(JSON.stringify(data))
  //循环所有项
  const treeData = cloneData.filter(father => {
    let branchArr = cloneData.filter(child => {
      //返回每一项的子级数组
      return father[id] === child[parentId]
    });
    branchArr.length > 0 ? father.children = branchArr : ''
    //返回第一层
    return father[parentId] === rootId
  })
  return treeData !== '' ? treeData : data
}

/**
 * 获取当前域名
 *  http://www.baidu.com
 * @returns {string}
 */
export function getCurrentDomain() {
  return window.location.protocol + '//' + window.location.host
}
